package com.ensa.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.util.Log;

import com.thoughtworks.xstream.XStream;


public class XMLParse {

	private XStream xstream;
	private BufferedReader br;
	private BufferedWriter bw;
	//private String fichier;
	
	public XMLParse(){
		//this.fichier=fichier;
		xstream = new XStream();
		xstream.alias("personne", Personne.class);
		xstream.alias("personnes", PersonList.class);
		xstream.addImplicitCollection(PersonList.class, "list");
	}

	public void toXML(PersonList list, FileOutputStream out) throws IOException {
		String xml = xstream.toXML(list);
		bw = new BufferedWriter(new OutputStreamWriter(out));
		bw.write(xml);
		bw.flush();
		bw.close();
		
	}
	public PersonList fromXML(InputStream is) throws IOException {
		br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		String temp;
		String xml = null;
		while ((temp = br.readLine()) != null) {
			if (xml == null) {
				xml = temp;
			} else {
				xml += "\n" + temp;
			}
		}
		PersonList pList;
		if(xml==null) {
			pList = new PersonList(); 
		}
		else {
			pList = (PersonList) xstream.fromXML(xml);
		}
		return pList;
	}
	
	public void UpdateList(int indice, PersonList pList, Personne personne){
		pList.getList().get(indice).setNom(personne.getNom());
		pList.getList().get(indice).setAge(personne.getAge());
		pList.getList().get(indice).setAdresse(personne.getAdresse());
		pList.getList().get(indice).setPhoto(personne.getPhoto());
		pList.getList().get(indice).setTel(personne.getTel());
	}
	
	public void AjouterList(PersonList pList, Personne personne){
		pList.getList().add(personne);
	}

}
